import { Component, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {ActivatedRoute, Router} from '@angular/router';
import {HandoverobjModel} from '../handoverobj.model';
import {DutyService} from '../duty.service';
import {BasePage} from '../../base.page';
import {ConfirmationService} from 'primeng/primeng';
import {MessageService} from 'primeng/components/common/messageservice';
import {PUblicMethod} from '../../services/PUblicMethod';

@Component({
  selector: 'app-create-handover',
  templateUrl: './create-handover.component.html',
  styleUrls: ['./create-handover.component.scss']
})
export class CreateHandoverComponent extends BasePage implements OnInit {
    title: string = '创建交接班';
    myForm: FormGroup;
    formObj: HandoverobjModel;
    acceptors: Array<object>;
    editable: boolean = false;
    constructor(private fb: FormBuilder,
                private router: Router,
                private activedRouter: ActivatedRoute,
                private dutyService: DutyService,
                public c: ConfirmationService,
                public m: MessageService) {
        super(c, m);
        // this.acceptors = [
        //     {
        //         'label': '张珊',
        //         'value': '张珊'
        //     },
        //     {
        //         'label': '李思',
        //         'value': '李思'
        //     },
        //     {
        //         'label': '王舞',
        //         'value': '王舞'
        //     },
        //     {
        //         'label': '七喜',
        //         'value': '七喜'
        //     }
        // ];
    }

    ngOnInit() {
        this.formObj = new HandoverobjModel();
        this.initMyForm();
        this.getUserDutyMsg();
        this.getNextDutyPerson();
        this.getRouterParam();
    }
    initMyForm() {
        this.myForm = this.fb.group({
            content: [null, Validators.required]
        });
    }
    getUserDutyMsg() {
        this.dutyService.getUserDutyMsg().subscribe(res => {
           if (res['errcode'] === '00000') {
               this.formObj.shift_name = res['datas'][0]['sid'];
               this.formObj.shift_id = res['datas'][0]['did'];
               this.handleShiftTime(res);
           }else {
               this.alert('获取当前用户班次信息失败', 'error');
           }
        });
    }
    handleShiftTime(res) {
        let beginTime1 = res['datas'][0]['begin_time_1'];
        let endTime1 = res['datas'][0]['end_time_1'];
        let beginTime2 = res['datas'][0]['begin_time_2'];
        let endTime2 = res['datas'][0]['end_time_2'];
        if ( beginTime1 && !beginTime2) {
           this.formObj.shift_time = `${PUblicMethod.formateMiniteTime(beginTime1)} - ${PUblicMethod.formateMiniteTime(endTime1)}`;
        }else if ( beginTime1 && beginTime2) {
           this.formObj.shift_time = `${PUblicMethod.formateMiniteTime(beginTime1)} - ${PUblicMethod.formateMiniteTime(endTime1)} | ${PUblicMethod.formateMiniteTime(beginTime2)} - ${PUblicMethod.formateMiniteTime(endTime2)}`;
        }
    }
    getNextDutyPerson() {
        this.dutyService.getNextDutyPerson().subscribe(res => {
            if (res['errcode'] === '00000') {
               this.acceptors = PUblicMethod.formateFlexDropDown(res['datas'], 'per_name', 'per');
                this.activedRouter.queryParams.subscribe(param => {
                    if (param['datas']) {
                        this.title = '编辑交接班';
                        this.editable = true;
                        this.formObj = new HandoverobjModel(JSON.parse(param['datas']));
                    }else {
                        this.formObj.acceptor = this.acceptors[0]['value']['label'];
                        this.formObj.acceptor_pid = this.acceptors[0]['value']['value'];
                    }
                });

            }else {
                this.alert('获取下一次值班人员失败', 'error');
            }
        });
    }
    isFieldValid(field: string): boolean {
        return PUblicMethod.isFieldValid(this.myForm, field);
    }
    resetSelectAccept() {
        if (typeof this.formObj.acceptor === 'object') {
            this.formObj.acceptor_pid = this.formObj.acceptor['value'];
            this.formObj.acceptor = this.formObj.acceptor['label'];
        }
    }
    submit() {
        this.resetSelectAccept();
        if (this.myForm.valid){
            this.dutyService.addHandover(this.formObj).subscribe(res => {
               if (res === '00000'){
                   this.alert('新增成功');
                   this.goBack();
               }else {
                   this.alert(`新增失败 + ${res}`, 'error');
               }
            });
        }else {
            PUblicMethod.validateAllFormFields(this.myForm);
        }
    }
    save() {
        this.resetSelectAccept();
        this.dutyService.saveHandover(this.formObj).subscribe(res => {
          if (res === '00000') {
            this.alert('保存成功');
            this.goBack();
          }else {
            this.alert(`保存失败 + ${res}`, 'error');
          }
        });
    }
    goBack() {
        this.router.navigate(['../handoveroverview'], {relativeTo: this.activedRouter})
    }

//    EDIT
    getRouterParam() {
      this.activedRouter.queryParams.subscribe(param => {
        if (param['datas']) {
            this.title = '编辑交接班';
            this.editable = true;
            this.formObj = new HandoverobjModel(JSON.parse(param['datas']));
        }

      });
    }
}
